from datetime import timedelta
from django.utils import timezone
from django.http import JsonResponse
from django.views.generic.base import TemplateView
from django.db.models import Count
from deploy.models import DeployPool
from envx.models import Env


def get_deploy_count(request):
    """按天返回近两个月的发布单数量，如：[{'08-10': 3}, {'08-11', 2}, ...]"""
    return_list = []
    now = timezone.now()
    two_month = now - timedelta(days=60)
    select = {'day': 'date(add_date)'}
    env = request.GET.get('env', 'ALL')
    if env != 'ALL':
        env_id = Env.objects.get(name=env).id
        two_month_deploy_qs = DeployPool.objects.filter(env_name__id=env_id).filter(
            add_date__range=(two_month, now)).extra(select=select).values('day').distinct().\
            order_by('day').annotate(number=Count('add_date'))
    else:
        two_month_deploy_qs = DeployPool.objects.filter(
            add_date__range=(two_month, now)).extra(select=select).values('day').distinct().\
            order_by('day').annotate(number=Count('add_date'))

    for item in two_month_deploy_qs:
        item_dict = {}
        # print("#" * 10, type(item['day']), item['day'], "#" * 10, sep='\n')
        item_key = item['day'].split('-', 1)[1]

        item_dict[item_key] = item["number"]
        return_list.append(item_dict)

    return JsonResponse(return_list, safe=False)


class DeployCountView(TemplateView):
    template_name = "deploy/deploy_count.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["current_page_name"] = "发布数据"
        return context


def get_app_deploy_count(request):
    """发布单数前10应用统计"""
    return_list = []
    app_deploy_qs = DeployPool.objects.values('app_name__name').distinct().annotate(
        number=Count('app_name')).order_by('-number')[:10]

    for item in app_deploy_qs:
        item_dict = {}
        item_key = item["app_name__name"]
        item_dict[item_key] = item["number"]
        return_list.append(item_dict)

    return JsonResponse(return_list, safe=False)


class AppDeployCountView(TemplateView):
    template_name = "deploy/app_deploy_count.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["current_page_name"] = "应用统计"
        return context
